

//
//  SelectSpecView.m
//  SelectSpec
//
//  Created by 吴欧 on 20/10/21.
//  Copyright © 2020 honglutec. All rights reserved.
//


#import "SelectSpecView.h"
#import "SepecModel.h"
#import "SepecConfig.h"
#import "CountView.h"
static NSString * const sepceCellID = @"sepecCellID";
static NSString * const headerViewID = @"headerViewID";
static NSString * const footerViewID = @"footerViewID";
#define SCREEN_BOUNDS   [UIScreen mainScreen].bounds
#define SCREEN_HEIGHT   [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH    [[UIScreen mainScreen] bounds].size.width
#define CommonGrayWhite [UIColor colorWithRed:222/255.0 green:223/255.0 blue:224/255.0 alpha:1] //分割线常用颜色
// 屏幕尺寸
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScreenBounds [UIScreen mainScreen].bounds
#define MaxX(v)            CGRectGetMaxX((v).frame) //横坐标加上控件的宽度
#define MaxY(v)            CGRectGetMaxY((v).frame) //纵坐标加上控件的高度
#define WI(v)           (v).frame.size.width
#define HE(v)          (v).frame.size.height
#import "UICollectionViewLeftAlignedLayout.h"

// 字体
#import "KNPhotoBrowser.h"


//UICollectionViewFlowLayout 我对其自定义有问题

@interface AddAttriCollReusableView : UICollectionReusableView

@property (nonatomic, retain)UILabel *headerLab;

@property (nonatomic, assign)NSInteger section;


- (void)setAttriHeaderTitle:(NSString *)title;
- (void)setAttriFooterTitle:(NSString *)title;

@end

@implementation AddAttriCollReusableView

- (void)setAttriHeaderTitle:(NSString *)title{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 31)];
    view.tag = _section+10;
    [self addSubview:view];
    UIView *line = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, kScreenW - 10, 1)];
    line.backgroundColor = [UIColor grayColor];
    [view addSubview:line];
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(14, 1, kScreenW - 2*14, 30)];
    lab.textColor = [UIColor darkGrayColor];
    lab.font = DYFont(15);
    [view addSubview:lab];
    self.headerLab = lab;
    self.headerLab.text = title;
}

- (void)setAttriFooterTitle:(NSString *)title{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 35)];
    [self addSubview:view];
}


@end



@interface sepecCell : UICollectionViewCell

@property (strong, nonatomic) UILabel *sepeclabel;
@property (nonatomic) SepecDetailModel *sepceModel;
@property (nonatomic) UIEdgeInsets contentInsets;

@end

@implementation sepecCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame: frame]) {
        
        _sepeclabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 35)];
        _sepeclabel.textAlignment = NSTextAlignmentCenter;
        _sepeclabel.userInteractionEnabled = NO;
        _sepeclabel.textColor = [UIColor blackColor];
        _sepeclabel.font = DYFont(15);
        
        [self.contentView addSubview:_sepeclabel];
    }
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect bounds = self.contentView.bounds;
    CGFloat width = bounds.size.width - self.contentInsets.left - self.contentInsets.right;
    CGRect frame = CGRectMake(0, 0, width, self.sepceModel.contentSize.height);
    self.sepeclabel.frame = frame;
    self.sepeclabel.center = self.contentView.center;
}

@end


@interface SelectSpecView ()<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, KNPhotoBrowserDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray<NSString *> *tagsMutableArray;
@property (nonatomic, retain)SepecConfig *config;
@property (nonatomic, retain)UIView *contentView;
@property (nonatomic, retain)UIView *bgView;

@property (nonatomic, retain)UILabel *spec_price;
@property (nonatomic, retain)UILabel *specLab;

@property (nonatomic, copy) NSString *price;
@property (nonatomic, assign) NSInteger priceid;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign)BOOL iscompelete;//判断是否选择完全
@property (nonatomic, strong) NSMutableArray *tempSelectArr;//临时存储选择中的模型
@property (nonatomic, strong) NSMutableArray *preflagarr; // 已选属性
@property (nonatomic, strong) UIImageView *goodsImageView;
@property (nonatomic, strong) UILabel *stockLb; // 库存

@property (nonatomic, strong) UIButton *actionBtn;

@property (nonatomic, weak) KNPhotoBrowser *photoBrowser;
@property (nonatomic, strong) NSMutableArray *itemsArr;

@end

@implementation SelectSpecView

+ (SelectSpecView*)selectSpecViewWithdataArr:(NSArray<SepecModel *> *)dataArr {
        
    // 初始化
    SelectSpecView *sepecView = [[SelectSpecView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) withDataArr:dataArr];
    
    // 取出未选择的
    NSMutableArray *strs = [NSMutableArray array];
    for (SepecModel *demodel in dataArr) {
        [strs addObject:demodel.name_sepec];
    }
    sepecView.compeleteStr = [strs componentsJoinedByString:@","];

    [sepecView show:SpecSelectTypeBuyNow];
    [[UIApplication sharedApplication].keyWindow addSubview:sepecView];
    return sepecView;
}

- (void)show:(SpecSelectType)type {
    _type = type;
    
    if (type == SpecSelectTypeAddCart) {
        [_actionBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
        _actionBtn.backgroundColor = KHexColor(@"#F67605");
    }else if(type == SpecSelectTypeBuyNow){
        [_actionBtn setTitle:@"立即购买" forState:UIControlStateNormal];
        _actionBtn.backgroundColor = KHexColor(@"#3E8BF8");
    }
    
    self.hidden = self.contentView.hidden= self.bgView.hidden = NO;
    self.bgView.alpha = 0;
    [UIView animateWithDuration:0.5f animations:^{
        self.bgView.alpha = 1;
        self.contentView.frame = CGRectMake(0, KScreenHeight - self.config.height, kScreenW, self.config.height);
    }];
}

- (void)hiddenView{
    [UIView animateWithDuration:0.3f animations:^{
        self.contentView.frame = CGRectMake(0, kScreenH, kScreenW, self.config.height);
        self.bgView.alpha = 0;
    } completion:^(BOOL finished) {
        [self triggerSelectStatus];
        self.hidden = self.contentView.hidden=self.bgView.hidden = YES;
    }];
   }
- (void)setDataArr:(NSArray<SepecModel *> *)dataArr{
    _dataArr = dataArr;
    [self.collectionView reloadData];
}

- (instancetype)initWithFrame:(CGRect)frame withDataArr:(NSArray<SepecModel *> *)dataArr{
     [self setupConfig];
    self.dataArr = dataArr;
    if (self = [super initWithFrame:frame]) {
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        bgView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.3];
        [self addSubview:bgView];
        bgView.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenView)];
        [bgView addGestureRecognizer:tap];
        
        UIView *contentview = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenH, kScreenW, _config.height)];
        contentview.backgroundColor = [UIColor whiteColor];
        bgView.hidden = YES;
        [self addSubview:contentview];
        
        [contentview addRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadii:CGSizeMake(20, 20)];
        
        self.contentView = contentview;
        self.bgView = bgView;
        [self otherViews];
        
        if (dataArr.count > 0) {
            [self addInitCollectView];
        }else {
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(5, 125, kScreenW - 10, 0.5)];
            line.backgroundColor = CSplitLineColor;
            [contentview addSubview:line];

            UIView *countbgview = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(line.frame), kScreenW, 49)];
            countbgview.backgroundColor = [UIColor whiteColor];
            [contentview addSubview:countbgview];

            UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, kScreenW/2, 39)];
            lab.text = @"购买数量: ";
            lab.textColor = [UIColor blackColor];
            lab.font = DYFont(15);
            [countbgview addSubview:lab];

            CountView *view = [[CountView alloc]initWithFrame:CGRectMake(WI(countbgview) - 155, 19/2, 140, 30)];
            view.count = 1;
            view.goodstock = 1000000;//可选择的最大销量
            view.CountBlock = ^(NSInteger count){
             self.num = count;
            };
            [countbgview addSubview:view];
        }
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(15, HE(self.contentView) - AUTOY(_config.bottomBarHeight), kScreenW - 30, AUTOY(40));
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = AUTOY(40)/ 2.0;
        btn.backgroundColor = KHexColor(@"#3E8BF8");
        [self.contentView addSubview:btn];
        [btn setTitle:@"立即购买" forState:UIControlStateNormal];
        btn.titleLabel.font = DYBlodFont(15);
        [btn setTitleColor:[UIColor whiteColor] forState:0];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        _actionBtn = btn;
    }
    return self;
}
#pragma mark - 头部视图 需要展示数据 如销量之类的 可在这里添加
- (void)otherViews{
    
    _goodsImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 15, 100, 100)];
    _goodsImageView.contentMode = UIViewContentModeScaleAspectFill;
    _goodsImageView.clipsToBounds = YES;
    [_goodsImageView sd_setImageWithURL:[NSURL URLWithString:_goods.pic] placeholderImage:IMAGE_NAMED(@"noImage")];
    [self.contentView addSubview:_goodsImageView];
    
    _goodsImageView.userInteractionEnabled = YES;
    [_goodsImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidClick:)]];
    
    KNPhotoItems *items = [[KNPhotoItems alloc] init];
    items.sourceView = _goodsImageView;
    [self.itemsArr addObject:items];
        
    UILabel *price = [[UILabel alloc] initWithFrame:CGRectMake(MaxX(_goodsImageView)+10, 15, kScreenH/2, 30)];
    price.textColor = [UIColor redColor];
    price.font = DYFont(18);
    self.spec_price = price;
    [self.contentView addSubview:price];
    price.text = @"￥0.00";
    
    // 库存
    UILabel *stockLb = [[UILabel alloc] initWithFrame:CGRectMake(MaxX(_goodsImageView)+10, MaxY(price), kScreenH/2, 30)];
    stockLb.textColor = [UIColor darkGrayColor];
    stockLb.font = DYFont(15);
    stockLb.text = @"库存：0";
    self.stockLb = stockLb;
    [self.contentView addSubview:stockLb];

    UILabel *sepelab = [[UILabel alloc] initWithFrame:CGRectMake(MaxX(_goodsImageView)+10, MaxY(stockLb), kScreenH/2, 30)];
    sepelab.font = DYFont(15);
    self.specLab = sepelab;
    [self.contentView addSubview:sepelab];
    
    NSString *str = @"";
    for (SepecModel *mo in _dataArr) {
        str = [NSString stringWithFormat:@"%@ %@",str,mo.name_sepec];
    }
    sepelab.text = [NSString stringWithFormat:@"请选择：%@", str];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:IMAGE_NAMED(@"good_pop_close") forState:UIControlStateNormal];
    btn.frame = CGRectMake(kScreenW - 55, 5, 50, 40);
    [btn addTarget:self action:@selector(hiddenView) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:btn];
}

- (void)setGoods:(HEGoodsModel *)goods {
    _goods = goods;

    [self resetHead];
}

- (void)resetHead {
    [self refresshHeadInfoWithImages:_goods.pic price:_goods.price stock:_goods.stock];
}

- (void)refreshByselectItem:(compareSepecModel *)model {
    [self refresshHeadInfoWithImages:model.spec_pic price:model.spec_price stock:model.stock];
}

- (void)refresshHeadInfoWithImages:(NSString *)urls price:(NSString *)price stock:(NSInteger)stock {
    [_goodsImageView sd_setImageWithURL:[NSURL URLWithString:urls] placeholderImage:IMAGE_NAMED(@"noImage")];
    _spec_price.text = [NSString stringWithFormat:@"￥%@", [NSDecimalNumber rounding:price afterPoint:2]];
    _stockLb.text = [NSString stringWithFormat:@"库存：%ld", (long)stock];
}
 

#pragma mark - UICollectionView基础属性设置
- (void)setupConfig{
    _num = 1;
    _config = [[SepecConfig alloc]init];
    
    _config.height = KScreenHeight / 2.0  + 150;
    _config.bottomBarHeight = 50 + ([[UIApplication sharedApplication] statusBarFrame].size.height > 20 ? 34 : 0);
    _config.topHeadHeight = 130;
    _config.contentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
   _config.sepecInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    _config.sepecBorderWidth = 1;
    _config.sepeccornerRadius = 5;
    _config.sepecBackgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.0];
    _config.sepecSelectedBackgroundColor = [UIColor redColor];
    _config.sepecSelectedBorderColor = [UIColor redColor];
    _config.sepecBorderColor = [UIColor darkGrayColor];
    _config.sepecFont = [UIFont systemFontOfSize:14];
    _config.sepecSelectedFont = [UIFont systemFontOfSize:14];
    _config.sepecTextColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    _config.sepecSelectedTextColor = [UIColor redColor];
    
    _config.sepecHeight = 28;
    _config.mininumsepecWidth = 0;
    _config.maximumsepecWidth = CGFLOAT_MAX;
    _config.lineSpacing = 10;
    _config.interitemSpacing = 15;
}

#pragma mark - collectionView
- (void)addInitCollectView{

    //1.初始化layout
//     UICollectionViewFlowLayout*layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.minimumInteritemSpacing = 5;
//    layout.minimumLineSpacing = 5;
//    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//    layout.itemSize = CGSizeMake(kScreenW/5, 40);
//    //设置collectionView滚动方向
//    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    
   UICollectionViewLeftAlignedLayout *layout = [[UICollectionViewLeftAlignedLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//        layout.minimumLineSpacing = 10*WidthRatio;
        layout.minimumInteritemSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 10, 15);
    

    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, AUTOY(_config.topHeadHeight), kScreenW, HE(_contentView) - AUTOY(_config.topHeadHeight) - AUTOY(_config.bottomBarHeight)) collectionViewLayout:layout];
    [self.collectionView registerClass:[sepecCell class] forCellWithReuseIdentifier:sepceCellID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID];
     [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerViewID];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    _collectionView.allowsSelection = YES;
    [self.contentView addSubview:self.collectionView];
}
#pragma mark - 确定规格选择---根据项目需要返回指定数据
- (void)btnAction:(UIButton *)sender{
//    BOOL hasComp = [self triggerSelectStatus];
    
    // 无规格
    if (!self.dataArr.count) {
        [self hiddenView];

        if (self.actionBtnBlock) {
            self.actionBtnBlock(_priceid, _goods.price, _num, _compeleteStr);
        }
        return;
    }
    
    // 有规格
    BOOL hasComp = _iscompelete;

    if (hasComp) {
        [self hiddenView];
        
        if (self.actionBtnBlock) {
            self.actionBtnBlock(_priceid, _price, _num, _compeleteStr);
        }
    }
    
    for (SepecModel *sepModel in _dataArr) {
       Boolean flag = false;
       for (SepecModel *select in _preflagarr) {
           if (select.id_sepec == sepModel.id_sepec) {
               flag = true;
               break;
           }
       }
       if (!flag) {
           [Dialog toast:[NSString stringWithFormat:@"请选择：%@", sepModel.name_sepec] delay:2.0];
           return;
       }
   }
}

- (BOOL)triggerSelectStatus {
    if (!_iscompelete) {
         if (_inCompleteBlock) {
             _inCompleteBlock(0, @"0.00",  1, _compeleteStr);
             return NO;
         }
     }else{
         if (_finishSelectedBlock) {
             _finishSelectedBlock(_priceid, _price, _num, _compeleteStr);
             return YES;
         }
     }
    return NO;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SepecModel *model = _dataArr[section];
    return model.arr_sepec.count;
}
// 返回格子有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    sepecCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sepceCellID forIndexPath:indexPath];
    
    SepecModel *model = self.dataArr[indexPath.section];
    SepecDetailModel *sepecModel = model.arr_sepec[indexPath.row];
    cell.sepceModel = sepecModel;
    cell.sepeclabel.text = sepecModel.name_sepec;
    cell.layer.cornerRadius = self.config.sepeccornerRadius;
    cell.layer.masksToBounds = self.config.sepeccornerRadius > 0;
//    cell.contentInsets = self.config.sepecInsets;
    cell.layer.borderWidth = self.config.sepecBorderWidth;
    [self setCell:cell selected:sepecModel.selected];
    
    return cell;
}

- (void)setCell:(sepecCell *)cell selected:(BOOL)selected {
    
    if (selected) {
        cell.sepeclabel.font = self.config.sepecSelectedFont;
        cell.sepeclabel.textColor = self.config.sepecSelectedTextColor;
        cell.layer.borderColor = self.config.sepecSelectedBorderColor.CGColor;
    }else {
        cell.sepeclabel.font = self.config.sepecFont;
        cell.sepeclabel.textColor = self.config.sepecTextColor;
        cell.layer.borderColor = self.config.sepecBorderColor.CGColor;
    }
}

////头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
      
        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID forIndexPath:indexPath];
        SepecModel *model = _dataArr[indexPath.section];
        [headerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];//每次刷新 移除子视图 不然会重叠
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(5, 0, kScreenW - 10, 0.5)];
        line.backgroundColor = CSplitLineColor;
        [headerView addSubview:line];
        
        UILabel *sepecNamelab = [[UILabel alloc]initWithFrame:CGRectMake(14, 1, kScreenW - 2*14, 30)];
        sepecNamelab.font = DYFont(15);
        sepecNamelab.text = model.name_sepec;
        [headerView addSubview:sepecNamelab];
      

        return headerView;
    }else{
        if (_dataArr.count-1 == indexPath.section) {
           UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerViewID forIndexPath:indexPath];
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(5, 0, kScreenW - 10, 1)];
            line.backgroundColor = CSplitLineColor;
            [headerView addSubview:line];

            UIView *countbgview = [[UIView alloc]initWithFrame:CGRectMake(0, 1, kScreenW, 49)];
            countbgview.backgroundColor = [UIColor whiteColor];
            [headerView addSubview:countbgview];
            
            UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, kScreenW/2, 39)];
            lab.text = @"购买数量: ";
            lab.textColor = [UIColor blackColor];
            lab.font = DYFont(15);
            [countbgview addSubview:lab];
            
            CountView *view = [[CountView alloc]initWithFrame:CGRectMake(WI(countbgview) - 155, 19/2, 140, 30)];
            view.count = 1;
            view.goodstock = 1000000;//可选择的最大销量
            view.CountBlock = ^(NSInteger count){
                self.num = count;
            };
            [countbgview addSubview:view];
            return headerView;
        }else{
            return nil;
        }
    }
//  return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreenW, 31);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (_dataArr.count - 1 == section) {
         return CGSizeMake(kScreenW, 70);
    }
    return CGSizeMake(0, 0);
}


#pragma mark - ......::::::: UICollectionViewDelegate :::::::......
// 选中操作
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SepecModel *model = self.dataArr[indexPath.section];
    SepecDetailModel *sepecModel = model.arr_sepec[indexPath.item];
    
    sepecModel.selected =  !sepecModel.selected;
    
    if (sepecModel.selected) {
        for (SepecDetailModel *mo in model.arr_sepec) {
            if (sepecModel != mo) {
                mo.selected = NO;
            }
        }
    }
    
    _tempSelectArr = [NSMutableArray array];
    _preflagarr = [NSMutableArray array];
    for (SepecModel *model in _dataArr) {
        for (SepecDetailModel *demodel in model.arr_sepec) {
            if (demodel.selected == YES) {
                [_tempSelectArr addObject:demodel];
                [_preflagarr addObject:model];
                break;
            }
        }
    }
    
    if (_preflagarr.count == _dataArr.count) {//选择的个数等于组数
        NSString *str = @"";
        NSMutableArray *matchs = [NSMutableArray array];

        for (SepecDetailModel *demodel in _tempSelectArr) {
            str = [NSString stringWithFormat:@"%@ %@",str, demodel.name_sepec];
            [matchs addObject:demodel.name_sepec];
        }
        self.specLab.text  = [NSString stringWithFormat:@"已选择：%@",str];
        
        //确定选择哪个sku
        NSString *matchStr = [NSString stringWithFormat:@"规格:%@", [matchs componentsJoinedByString:@","]];
        
        for (compareSepecModel *compareModel in _comparedataArr) {
            if ([matchStr isEqualToString:compareModel.matchStr]) {
                self.spec_price.text = [NSString stringWithFormat:@"￥%0.2f", compareModel.spec_price];
                self.price = compareModel.spec_price;
                self.priceid = compareModel.goodspriceid;
                [self refreshByselectItem:compareModel];
            }
        }
        _iscompelete = YES;
        _compeleteStr = str;
    }else{
        NSMutableArray *dataCopy = [NSMutableArray array];
        dataCopy = [_dataArr mutableCopy];
        NSString *str = @"";
        for (SepecModel *demodel in _preflagarr) {
            [dataCopy removeObject:demodel];//移除已经选择的
        }
        for (SepecModel *demodel in dataCopy) {//取出未选择的
           str = [NSString stringWithFormat:@"%@ %@",str,demodel.name_sepec];
        }
        self.specLab.text  = [NSString stringWithFormat:@"请选择：%@",str];
        [self resetHead];
        
        _compeleteStr = str;
        _iscompelete = NO;//状态为NO
    }
    
    [collectionView reloadData];
}



#pragma mark - ......::::::: UICollectionViewDelegateFlowLayout :::::::......

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    SepecModel *model = self.dataArr[indexPath.section];
    SepecDetailModel *sepecModle = model.arr_sepec[indexPath.row];
    CGFloat width = sepecModle.contentSize.width + self.config.sepecInsets.left + self.config.sepecInsets.right;
    if (width < self.config.mininumsepecWidth) {
        width = self.config.mininumsepecWidth;
    }
    if (width > self.config.maximumsepecWidth) {
        width = self.config.maximumsepecWidth;
    }
    
    return CGSizeMake(width, self.config.sepecHeight);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return self.config.interitemSpacing;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return self.config.lineSpacing;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return self.config.contentInsets;
}


#pragma mark -
- (void)imageViewDidClick:(UITapGestureRecognizer *)tap{
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    photoBrowser.itemsArr = [self.itemsArr copy];
//    photoBrowser.isNeedPageControl = true; // if it has video to play , I do not suggest you to use PageControl
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedRightTopBtn = true;
    photoBrowser.isNeedPictureLongPress = true;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;
    
    photoBrowser.currentIndex = 0;
    photoBrowser.delegate = self;
    [photoBrowser present];
    
    _photoBrowser = photoBrowser;
}

- (NSMutableArray *)itemsArr{
    if (!_itemsArr) {
        _itemsArr = [NSMutableArray array];
    }
    return _itemsArr;
}



#pragma mark - delegate

/* photoBrowser 右上角按钮的点击 */
- (void)photoBrowserRightOperationAction{
   
   __weak typeof(self) weakself = self;
   KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"保存"].mutableCopy destructiveArray:@[@"0"].mutableCopy actionSheetBlock:^(NSInteger buttonIndex) {
       if (buttonIndex == 0) {

           [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
       }
   }];
   
   [actionSheet show];
}

/// long press
/// @param photoBrowser pb
/// @param longPress press
- (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
   if (longPress.state == UIGestureRecognizerStateBegan) {
       [photoBrowser setImmediatelyPlayerRate:2];
   }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
       [photoBrowser setImmediatelyPlayerRate:1];
   }
}


- (void)toSaveImage:(NSURL *)url {
   SDWebImageManager *manager = [SDWebImageManager sharedManager];
   if ([manager cacheKeyForURL:url]) {
      [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
          // 保存图片到相册中
          UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
       }];
       return;
   }
   else {
       //从网络下载图片
       NSData *data = [NSData dataWithContentsOfURL:url];
       UIImage *img = [UIImage imageWithData:data];
       // 保存图片到相册中
       UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
   }
}

//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
 contextInfo:(void *)contextInfo {
   if (error != NULL) {
       [Dialog toast:@"图片保存失败" delay:2.0];
   }
   else  // No errors
   {
       [Dialog toast:@"图片保存成功" delay:2.0];
   }
}

@end





